﻿#include "MyTextEdit.h"
#include <QMenu>
#include <QContextMenuEvent>
#include <QClipboard>
#include <QApplication>
#include <QString>
#include <QMimeData>

#include <QDebug>
#include <QMovie>

MyTextEdit::MyTextEdit(QWidget *parent) : QTextEdit(parent)
{
    initMunu();
    //this->setStyleSheet("font-family: '微软雅黑'; font: 16pt");
}

MyTextEdit::~MyTextEdit()
{
    QHash<QMovie*, QUrl>::const_iterator i;
    for (i = m_hasUrls.constBegin(); i != m_hasUrls.constEnd(); ++i)
    {
        delete i.key();
    }
    qDebug() << "MyTextEdit::~MyTextEdit()";
}

void MyTextEdit::contextMenuEvent(QContextMenuEvent *e)
{
     m_pMenu->exec(e->globalPos());
}


void MyTextEdit::initMunu()
{
    m_pMenu = new QMenu(this);
    QAction *Cut = new QAction(tr("Cut(&T)"),this);
    QAction *Copy = new QAction(tr("Copy(&C)"),this);
    QAction *Paste = new QAction(tr("Paste(&P)"),this);
    QAction *SelectAll = new QAction(tr("Select All(&A)"),this);
    QAction *Font = new QAction(tr("Font(&F)"),this);

    m_pMenu->addAction(Cut);
    m_pMenu->addAction(Copy);
    m_pMenu->addAction(Paste);
    m_pMenu->addAction(SelectAll);
    m_pMenu->addSeparator();
    m_pMenu->addAction(Font);

    connect(Cut,&QAction::triggered,this,&MyTextEdit::SltCut);
    connect(Copy,&QAction::triggered,this,&MyTextEdit::SltCopy);
    connect(Paste,&QAction::triggered,this,&MyTextEdit::SltPaste);
    connect(SelectAll,&QAction::triggered,this,&MyTextEdit::SltSelectAll);
    connect(Font,&QAction::triggered,this,&MyTextEdit::SltFont);
}

void MyTextEdit::SltSubAnimate(int)
{
    //使用QMovie中的当前帧替换掉富文本中的图片元素
    QMovie* movie = qobject_cast<QMovie*>(sender());
    //替换图片为当前帧
    document()->addResource(QTextDocument::ImageResource,m_hasUrls.value(movie),movie->currentPixmap());
    //刷新显示
    this->setLineWrapColumnOrWidth(lineWrapColumnOrWidth());
}

void MyTextEdit::SltAddEmotion(int faceid)
{
    QString&& file = QString("<img src=qrc:/face/resource/Face/%1.gif>").arg(faceid);

    //插入html描述的图片
    QTextCursor cursor = this->textCursor();
    cursor.insertHtml(file);
    //判断是否是相同的图片
    if(m_lstUrls.contains(faceid))
    {
        return;
    }else
    {
        m_lstUrls.append(faceid);
    }

    //创建QMovie以显示gif
    QMovie* movie = new QMovie(this);
    movie->setFileName(QString(":/face/resource/Face/%1.gif").arg(faceid));
    movie->setCacheMode(QMovie::CacheNone);

    m_hasUrls.insert(movie,QUrl(QString("qrc:/face/resource/Face/%1.gif").arg(faceid)));
    //绑定帧切换信号槽
    connect(movie,&QMovie::frameChanged,this,&MyTextEdit::SltSubAnimate);
    movie->start();
    this->setFocus();
}

void MyTextEdit::SltCut()
{
    this->cut();
}

void MyTextEdit::SltCopy()
{
    this->copy();
}

void MyTextEdit::SltPaste()
{
    this->paste();
}

void MyTextEdit::SltSelectAll()
{
    this->selectAll();
}

void MyTextEdit::SltFont()
{

}

